package com.snap.vseries.utils;

import android.app.ProgressDialog;
import android.content.Context;

import com.orhanobut.logger.Logger;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {
    public static ProgressDialog dialog;


    /**
     * 发送网络请求
     *
     * @param url  请求Url
     * @param body 请求体，如果有请求体则发送Post请求，反之发送Get请求
     */
    public static void getHttpRequest(String url, RequestBody body) {

        OkHttpClient client = new OkHttpClient();

        Request request = null;

        //Post请求
        if (body != null) {
            request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            //MediaType.parse("application/json"), jsonString
        } else {
            //Get请求
            request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
        }

        client.newCall(request).enqueue(new Callback() {
            /*请求失败时的回调*/
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.e("onFailure:" + e.getMessage());
            }

            /*请求成功时的回调*/
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Logger.e("ApiData:" + response.body().string());
            }
        });
    }


    /**
     * 显示等待框
     *
     * @param context
     */
    public static void startDialog(Context context) {
        dialog = new ProgressDialog(context);
        dialog.setMessage("数据加载。。。");
        dialog.setTitle("请稍后");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 关闭等待框
     */
    public static void stopDialog() {
        if (dialog != null) {

            dialog.dismiss();
        }
    }
}

